/*
   This example code is in the Public Domain (or CC0 licensed, at your option.)

   Unless required by applicable law or agreed to in writing, this
   software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
   CONDITIONS OF ANY KIND, either express or implied.
*/

#include <stdio.h>
#include <string.h>
#include <sys/param.h>

#include "user_gpio.h"
#include "user_system.h"
//#include "user_timer.h"
#include "user_tcp_client.h"

static const char *TAG = "main";

static void tcp_client_task(void *pvParameters)
{
    ESP_ERROR_CHECK( nvs_flash_init() );
    initialise_wifi();
    wait_for_ip();
    led_switch(ON);
    uint32_t mac_id = get_mac_id();
    while (1) {
        int sock = connect_to_server();
        if(0 > sock){
            led_switch(OFF);
            break;
        } 
        while (1) {
            uint32_t info = get_state();
            uint32_t state = mac_id | info;

            ESP_LOGI(TAG, "%08x",state);
            if(!tcp_send_data(sock,&state,4)) {
                led_switch(OFF);
                break;
            }
            led_toggle();
            vTaskDelay(1000 / portTICK_PERIOD_MS);
        }
        cloese_socket(sock);
    }
    vTaskDelete(NULL);
}

void app_main(void)
{
    printf_info();
    gpio_config_init();
    xTaskCreate(tcp_client_task, "tcp_client", 4096, NULL, 5, NULL);
}
